<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商品编码" prop="goodsId">
        <el-input
          v-model="queryParams.goodsId"
          placeholder="请输入商品编码"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!--      <el-form-item label="出仓信息" prop="outStockInfo">-->
      <!--        <el-input-->
      <!--          v-model="queryParams.outStockInfo"-->
      <!--          placeholder="请输入出仓信息"-->
      <!--          clearable-->
      <!--          size="small"-->
      <!--          @keyup.enter.native="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <el-form-item label="入仓信息" prop="inStockInfo">
        <el-input
          v-model="queryParams.inStockInfo"
          placeholder="请输入入仓信息"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
          <el-option label="待确定" :value="1"/>
          <el-option label="已确定" :value="2"/>
          <el-option label="已取消" :value="3"/>
        </el-select>
      </el-form-item>
      <el-form-item label="时间" prop="time">
        <el-date-picker
          v-model="queryParams.time"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          value-format="yyyy-MM-dd"
          end-placeholder="结束日期"></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-has-permi="['recovery:warehouse:train']"
        >移库
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="warehouseList" border>
      <el-table-column label="编号" align="center" type="index"/>
      <!--      <el-table-column label="出仓信息" align="center" prop="outStockInfo" />-->
      <el-table-column label="入仓信息" align="center" prop="inStockInfo"/>
      <el-table-column label="数量" align="center" prop="number"/>
      <el-table-column label="状态" align="center" prop="status">
        <template v-slot="scope">
          <el-tag v-if="scope.row.status === 1" type="warning">待确认</el-tag>
          <el-tag v-if="scope.row.status === 2" type="success">已确认</el-tag>
          <el-tag v-if="scope.row.status === 3" type="info">已取消</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" prop="createBy"/>
      <el-table-column label="创建时间" align="center" prop="createTime"/>
      <el-table-column label="更新人" align="center" prop="updateBy"/>
      <el-table-column label="更新时间" align="center" prop="updateTime"/>
      <el-table-column label="备注" align="center" prop="remark" show-overflow-tooltip/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template v-slot="scope">
          <el-button
            size="mini"
            type="text"
            :icon="checkUpdatePer(scope.row) ? 'el-icon-edit' : 'el-icon-search'"
            @click="handleUpdate(scope.row)"
          >{{ checkUpdatePer(scope.row) ? '修改' : '详情' }}
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-check"
            @click="handleConfirm(scope.row)"
            v-has-permi="['recovery:warehouse:confirm']"
            v-if="scope.row.status === 1"
          >确定
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-close"
            v-if="scope.row.status === 1"
            @click="handleCancel(scope.row)"
          >取消
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改出入库日志对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="80%" append-to-body :before-close="handleClose">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px" v-if="checkUpdatePer(form)">
        <el-row>
          <!--          <el-col :span="12">-->
          <!--            <el-form-item label="出仓库" prop="outStockId">-->
          <!--              <el-select-->
          <!--                v-model="form.outStockId"-->
          <!--                placeholder="请选择要移交的物品所在仓库"-->
          <!--                filterable style="width: 80%"-->
          <!--                @change="changeOutStock"-->
          <!--              >-->
          <!--                <el-option-->
          <!--                  v-for="item in outStockList"-->
          <!--                  :label="item.stockName"-->
          <!--                  :value="item.stockId"-->
          <!--                  v-show="outStockListByPageType(item)"-->
          <!--                  v-if="form.inStockId !== item.stockId"-->
          <!--                />-->
          <!--              </el-select>-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->

          <el-col :span="12">
            <el-form-item label="入仓库" prop="inStockId">
              <el-select
                v-model="form.inStockId"
                placeholder="请选择要移交的物品要前往的仓库"
                filterable style="width: 80%"
                @change="changeInStock"
              >
                <el-option
                  v-for="item in inStockList"
                  :label="item.stockName"
                  :value="item.stockId"
                  v-if="form.outStockId !== item.stockId"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注"/>
        </el-form-item>

        <el-row>
          <el-col :span="10">
            <el-form-item label="商品编码" prop="goodsId">
              <el-input
                v-model="goodsQuery.goodsId"
                placeholder="请输入要移库的商品编码"
                @keyup.enter.native="handleAddGoods"
                clearable
              />
            </el-form-item>
          </el-col>

          <el-col :span="10">
            <el-form-item label="回收编号" prop="collectId">
              <el-input
                type="number"
                v-model="goodsQuery.collectId"
                placeholder="请输入要移库的回收编号"
                @keyup.enter.native="handleAddGoods"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <div style="margin-top: 5px;margin-left: 5px;display: flex; align-items: center;justify-content: center">
              <el-button size="mini" type="primary" @click="handleAddGoods">添加</el-button>

              <div style="margin: auto">数量：{{ form.goodsList.length }}</div>
            </div>
          </el-col>
        </el-row>
      </el-form>

      <div style="margin: 10px 0">
        <el-button @click="handleExportGoods" v-if="!checkUpdatePer(form)" type="warning" plain>导出</el-button>
      </div>
      <el-table :data="form.goodsList" border max-height="500px">
        <el-table-column label="编号" align="center" type="index"/>
        <el-table-column label="原仓库" align="center" prop="oldStockName" show-overflow-tooltip/>
        <el-table-column label="商品编码" align="center" prop="goodsId" width="200"/>
        <el-table-column label="商品名称" align="center" prop="goodsName" show-overflow-tooltip/>
        <el-table-column label="串号" align="center" prop="imei" show-overflow-tooltip/>
        <el-table-column label="规格" align="center" prop="specs" show-overflow-tooltip/>
        <el-table-column label="验机详情" align="center" prop="testInfo" show-overflow-tooltip/>
        <el-table-column label="回收金额" align="center" prop="costPrice" />
        <el-table-column label="供应商" align="center" prop="supplierName" show-overflow-tooltip v-if="pageType === 'quote'" />
        <el-table-column label="回收编码" align="center" prop="collectId" v-if="pageType === 'quote'" />
        <el-table-column label="回收总数" align="center" prop="collectNum" v-if="pageType === 'quote'" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" v-if="checkUpdatePer(form)">
          <template v-slot="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handelDeleteTransfer(scope.row, scope)"
            >取消移库
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" v-if="checkUpdatePer(form)">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listWarehouse,
  getWarehouse,
  addWarehouse,
  updateWarehouse,
  confirmLogs,
  cancelLogs, exportWarehouseGoods
} from "@/api/recovery/warehouse";
import {listStockPower, listStock} from "@/api/recovery/stock";
import {listTransferGoods} from "@/api/recovery/goods";
import {delTransferGoods} from "@/api/recovery/transferGoods"
import {getInfo} from "@/api/login"
import userInfo from "@/views/system/user/profile/userInfo.vue";

export default {
  name: "Warehouse",
  components: {},
  data() {
    return {
      userInfo: undefined,
      pageType: undefined,
      goodsQuery: {
        pageNum: 1,
        pageSize: 50,
        //移库临时商品编码
        goodsId: undefined,
        collectId: undefined,
        stockId: undefined
      },
      typeOptions: [],
      goodsList: [],
      //出库可选列表
      outStockList: [],
      //入库可选列表
      inStockList: [],
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 出入库日志表格数据
      warehouseList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        number: null,
        outStockId: null,
        outStockInfo: null,
        inStockId: null,
        inStockInfo: null,
        status: null,
        goodsId: undefined,
        params: undefined,
        time: []
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        outStockId: [
          {required: true, message: "出仓库不能为空", trigger: "blur"}
        ],
        inStockId: [
          {required: true, message: "入仓库不能为空", trigger: "blur"}
        ]
      }
    };
  },
  created() {
    let arr = this.$route.path.split("/");
    this.pageType = arr[1]
    if (this.pageType !== "stock") {
      this.queryParams.params = {type: arr[1]}
    }
    this.getList();
    this.getStockListInit();
    this.getDicts("recovery_stock_type").then(response => {
      this.typeOptions = response.data;
    });

    getInfo().then(res => {
      console.log("当前用户信息: ", res);
      this.userInfo = res.user;
    })
  },
  methods: {
    //校验修改权限
    checkUpdatePer(row) {
      if (row.createBy === userInfo.userName) {
        if (row.status === 1)
          return true
      }

      return false;
    },
    outStockListByPageType(item) {
      if (this.pageType === "test") {
        if (item.type !== "test")
          return false
      }
      return true;
    },
    /** 提交移库 */
    handleConfirm(row) {
      this.$confirm("请仔细亲点商品，在确定！", "提示").then(() => {
        confirmLogs(row.id).then(res => {
          this.msgSuccess("操作成功！");
          this.getList();
        })
      }).catch(() => {
      });

    },
    /** 取消移库*/
    handleCancel(row) {
      this.$confirm("确定取消移库吗？", "提示").then(() => {
        cancelLogs(row.id).then(res => {
          this.msgSuccess("操作成功！");
          this.getList();
        })
      }).catch(() => {
      });
    },
    /** 取消移库*/
    handelDeleteTransfer(row, e) {
      if (row.id) {
        delTransferGoods(row.id).then(res => {
          this.form.goodsList.splice(e.$index, 1);
        })
      } else {
        this.form.goodsList.splice(e.$index, 1);
      }
    },
    handleClose() {
      this.$confirm("确定关闭吗?", "警告").then(() => {
        this.open = false;
      }).catch(() => {
      });
    },
    changeOutStock() {
      this.form.goodsList = [];
      this.outStockList.forEach(it => {
        if (this.form.outStockId === it.stockId)
          this.form.outStockInfo = it.stockName + "(" + this.getStockTypeLabel(it.type) + ")"
      })
    },
    changeInStock() {
      this.inStockList.forEach(it => {
        if (this.form.inStockId === it.stockId)
          this.form.inStockInfo = it.stockName + "(" + this.getStockTypeLabel(it.type) + ")"
      })
    },
    getStockTypeLabel(val) {
      let res = ""
      this.typeOptions.forEach(it => {
        if (it.dictValue === val)
          res = it.dictLabel;
      })
      return res;
    },
    /** 获取移交商品详情*/
    handleAddGoods() {
      if (!this.form.inStockId) {
        this.msgWarning("入仓库不能为空！");
        return;
      }
      if (!this.goodsQuery.goodsId && !this.goodsQuery.collectId) {
        this.msgWarning("请输入商品编码或回收编号");
        return;
      }
      listTransferGoods(this.goodsQuery).then(res => {
        let set = new Set();
        let arr = [];
        this.form.goodsList.forEach(it => {
          if (it.stockId !== this.form.inStockId) {
            if (!set.has(it.goodsId)) {
              arr.push(it);
              set.add(it.goodsId)
            }
          }
        })

        res.data.forEach(it => {
          if (it.stockId !== this.form.inStockId) {
            if (!set.has(it.goodsId)) {
              arr.push(this.tranGoodsInfo(it));
              set.add(it.goodsId)
            }
          }

        })
        this.form.goodsList = arr;
        this.msgSuccess("操作成功！已为您自动过滤不可操作或重复商品");
        this.goodsQuery.goodsId = null;
      })
    },
    tranGoodsInfo(item) {
      let name = "";
      for (let i = 0; i < this.inStockList.length; i++) {
        if (item.stockId === this.inStockList[i].stockId) {
          name = this.inStockList[i].stockName;
          break
        }
      }
      return {
        goodsId: item.goodsId,
        goodsName: item.goodsName,
        imei: item.goodsName,
        specs: item.printing,
        testInfo: item.testInfo,
        oldStockId: item.stockId,
        oldStockName: name,
        costPrice: item.costPrice
      };
    },
    /** 获取仓库信息*/
    getStockListInit() {
      listStock({}).then(res => {
        this.inStockList = res.rows;
      })
      listStockPower({}).then(res => {
        this.outStockList = res.rows;
      })
    },
    /** 查询出入库日志列表 */
    getList() {
      this.loading = true;
      listWarehouse(this.queryParams).then(response => {
        this.warehouseList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        number: null,
        outStockId: null,
        outStockInfo: null,
        inStockId: null,
        inStockInfo: null,
        remark: null,
        goodsList: [],
        status: 1
      };
      this.goodsQuery = {
        pageNum: 1,
        pageSize: 50,
        goodsId: undefined,
        collectId: undefined,
        stockId: undefined
      }
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      if(this.queryParams.time.length > 0) {
        if(!this.queryParams.params)
          this.queryParams.params = {
            startTime: undefined,
            endTime: undefined
          }
        this.queryParams.params.startTime = this.queryParams.time[0];
        this.queryParams.params.endTime = this.queryParams.time[1];
      }else {
        if(this.queryParams.params){
          this.queryParams.params.startTime = '';
          this.queryParams.params.endTime = '';
        }

      }
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "移库";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id;
      getWarehouse(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "出入库日志";
      });
    },
    /** 提交按钮 */
    submitForm() {
      if (!this.form.goodsList || this.form.goodsList.length === 0) {
        this.msgWarning("请添加要移交的商品！");
        return
      }
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateWarehouse(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addWarehouse(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 导出按钮操作 */
    handleExportGoods() {
      this.$confirm('是否确认导出数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        return exportWarehouseGoods(this.form);
      }).then(response => {
        this.download(response.msg);
      })
    }
  }
};
</script>
